/**
 * 
 */
package com.wskj.library.employer.controller;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.wskj.library.pojo.Employer;
import com.wskj.library.pojo.RoleInfo;
import com.wskj.library.service.EmployerService;
import com.wskj.library.service.impl.EmployerServiceImpl;
import com.wskj.util.RequestUtil;

/**
 * @author 胡洋
 * @describe
 * @Date 2018年3月22日下午6:11:24
 * @version 1.0
 */
@MultipartConfig
@WebServlet(urlPatterns = "/employer/add.do")
public class AddEmployerServlet extends HttpServlet {
	EmployerService emService = new EmployerServiceImpl();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<RoleInfo> roles = emService.queryAllRoles();
		req.setAttribute("roles", roles);
		req.getRequestDispatcher("/WEB-INF/page/employer/add.jsp").forward(req, resp);
	}

	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		Employer employer = RequestUtil.convertRequestToEntity(Employer.class, req);
		Part part = req.getPart("img");		
		//上传文件的名称....
		String name= part.getSubmittedFileName();		
		//获取文件的后缀名
		String ext =name.substring(name.lastIndexOf(".")+1) ;	
		//判断后缀名是否合法  .....		
		String fileName = UUID.randomUUID().toString() + "."+ext;		
		part.write("D:/img/employer/" + fileName);
		// 文件地址: 头像的地址
		String filePath = "http://192.168.3.1:8080/img/employer/" + fileName;
		employer.setE_img(filePath);
		boolean result = emService.saveEmployer(employer);
		resp.sendRedirect(req.getContextPath() + "/employer/list.do");
	
	};

	 
	  /*
	   private String getFileName(String header) {
		*//**
		 * String[] tempArr1 = header.split(";");代码执行完之后，在不同的浏览器下，tempArr1数组里面的内容稍有区别
		 * 火狐或者google浏览器下：tempArr1={form-data,name="file",filename="snmp4j--api.zip"}
		 * IE浏览器下：tempArr1={form-data,name="file",filename="E:\snmp4j--api.zip"}
		 *//*
		String[] tempArr1 = header.split(";");
		*//**
		 * 火狐或者google浏览器下：tempArr2={filename,"snmp4j--api.zip"}
		 * IE浏览器下：tempArr2={filename,"E:\snmp4j--api.zip"}
		 *//*
		String[] tempArr2 = tempArr1[2].split("=");
		// 获取文件名，兼容各种浏览器的写法
		String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
		
		return fileName.substring(fileName.lastIndexOf(".")+1);
	}*/

}
